<template>
  <div class="user-manage-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-subtitle">管理系统中的所有用户信息</p>
      </div>
      <div class="header-stats">
        <div class="stat-item">
          <div class="stat-number">{{ total }}</div>
          <div class="stat-label">总用户数</div>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <a-card class="search-card">
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
          <a-row :gutter="16" align="middle">
            <a-col :xs="24" :sm="8" :md="6">
              <a-form-item label="账号" class="search-item">
                <a-input 
                  v-model:value="searchParams.userAccount" 
                  placeholder="请输入账号" 
                  allow-clear 
                  class="search-input"
                >
                  <template #prefix>
                    <UserOutlined class="input-icon" />
                  </template>
                </a-input>
      </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="8" :md="6">
              <a-form-item label="用户名" class="search-item">
                <a-input 
                  v-model:value="searchParams.userName" 
                  placeholder="请输入用户名" 
                  allow-clear 
                  class="search-input"
                >
                  <template #prefix>
                    <ContactsOutlined class="input-icon" />
                  </template>
                </a-input>
      </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="8" :md="12">
              <div class="search-actions">
                <a-button @click="handleReset" class="reset-btn">
                  重置
                </a-button>
                <a-button type="primary" html-type="submit" class="search-btn">
                  <template #icon>
                    <SearchOutlined />
                  </template>
                  搜索
                </a-button>
              </div>
            </a-col>
          </a-row>
    </a-form>
      </a-card>
    </div>

    <!-- 用户列表 -->
    <div class="users-section">
      <a-card class="users-card">
        <!-- 统计信息 -->
        <div class="stats-bar">
          <div class="stats-info">
            <span class="total-count">共找到 {{ total }} 个用户</span>
          </div>
        </div>

        <!-- 用户表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
          :loading="loading"
          row-key="id"
          class="users-table"
    >
      <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'userInfo'">
              <div class="user-info-cell">
                <div class="user-avatar">
                  <a-avatar 
                    :size="40" 
                    :src="record.userAvatar"
                    class="avatar"
                  >
                    <template #icon>
                      <UserOutlined />
                    </template>
                  </a-avatar>
                </div>
                <div class="user-details">
                  <div class="user-name">{{ record.userName || '未设置' }}</div>
                  <div class="user-account">{{ record.userAccount }}</div>
                </div>
              </div>
        </template>
            
            <template v-if="column.dataIndex === 'userProfile'">
              <div class="user-profile">
                {{ record.userProfile || '暂无简介' }}
          </div>
            </template>
            
            <template v-if="column.dataIndex === 'userRole'">
              <a-tag v-if="record.userRole === 'admin'" color="red" class="role-tag">
                <template #icon>
                  <CrownOutlined />
                </template>
                管理员
              </a-tag>
              <a-tag v-else color="blue" class="role-tag">
                <template #icon>
                  <UserOutlined />
                </template>
                普通用户
              </a-tag>
            </template>
            
            <template v-if="column.dataIndex === 'createTime'">
              <div class="time-cell">
                <div class="date">{{ formatDate(record.createTime) }}</div>
                <div class="time">{{ formatTime(record.createTime) }}</div>
          </div>
        </template>
            
        <template v-if="column.dataIndex === 'updateTime'">
              <div class="time-cell">
                <div class="date">{{ formatDate(record.updateTime) }}</div>
                <div class="time">{{ formatTime(record.updateTime) }}</div>
              </div>
        </template>

            <template v-if="column.key === 'action'">
              <div class="action-buttons">
                <a-button 
                  danger 
                  size="small" 
                  @click="doDelete(record.id)"
                  class="delete-btn"
                >
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                  删除
                </a-button>
              </div>
        </template>
      </template>
    </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { listUserVoByPage, deleteUser } from '@/api/userController'
import { message, Modal } from 'ant-design-vue'
import { 
  UserOutlined, 
  ContactsOutlined, 
  SearchOutlined, 
  DeleteOutlined,
  CrownOutlined 
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: '8%',
    align: 'center'
  },
  {
    title: '用户信息',
    dataIndex: 'userInfo',
    width: '25%'
  },
  {
    title: '用户简介',
    dataIndex: 'userProfile',
    width: '20%'
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    width: '12%',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: '15%',
    align: 'center'
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: '15%',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: '5%',
    align: 'center',
    fixed: 'right'
  }
]

// 响应式数据
const loading = ref(false)
const dataList = ref([])
const total = ref(0)

// 搜索参数
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return dayjs(dateStr).format('YYYY-MM-DD')
}

// 格式化时间
const formatTime = (dateStr?: string) => {
  if (!dateStr) return '-'
  return dayjs(dateStr).format('HH:mm:ss')
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
  const res = await listUserVoByPage({
    ...searchParams,
  })
    
    if (res.data.code === 0) {
      dataList.value = res.data.data?.records ?? []
      total.value = res.data.data?.totalRow ?? 0
  } else {
      message.error('获取数据失败：' + res.data.message)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 页面加载时请求数据
onMounted(() => {
  fetchData()
})

// 分页配置
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 项，共 ${total} 项`,
    pageSizeOptions: ['10', '20', '50', '100']
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 删除用户
const doDelete = async (id: string) => {
  if (!id) return
  
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个用户吗？此操作不可恢复。',
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
  const res = await deleteUser({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    fetchData()
  } else {
          message.error('删除失败：' + res.data.message)
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        message.error('删除失败，请稍后重试')
  }
    }
  })
}

// 搜索用户
const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  searchParams.userAccount = undefined
  searchParams.userName = undefined
  searchParams.current = 1
  fetchData()
}
</script>

<style lang="scss" scoped>
.user-manage-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 24px;
  
  .header-content {
    .page-title {
      font-size: 28px;
      font-weight: 700;
      margin: 0 0 8px 0;
      color: #333;
    }
    
    .page-subtitle {
      font-size: 16px;
      color: #666;
      margin: 0;
    }
  }
  
  .header-stats {
    .stat-item {
      text-align: center;
      padding: 16px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 12px;
      color: white;
      min-width: 120px;
      
      .stat-number {
        font-size: 24px;
        font-weight: 700;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
}

.search-section {
  margin-bottom: 24px;
  
  .search-card {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    
    .search-item {
      margin-bottom: 0;
      
      :deep(.ant-form-item-label) {
        font-weight: 500;
        color: #333;
      }
    }
    
    .search-input {
      .input-icon {
        color: #999;
      }
    }
    
    .search-actions {
      display: flex;
      gap: 8px;
      justify-content: flex-end;
      
      .search-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
      }
      
      .reset-btn {
        &:hover {
          color: #667eea;
          border-color: #667eea;
        }
      }
    }
  }
}

.users-section {
  .users-card {
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    
    .stats-bar {
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;
      
      .stats-info {
        .total-count {
          color: #666;
          font-size: 14px;
        }
      }
    }
  }
}

.users-table {
  :deep(.ant-table) {
    .ant-table-thead > tr > th {
      background: #fafafa;
      font-weight: 600;
      color: #333;
      border-bottom: 2px solid #f0f0f0;
    }
    
    .ant-table-tbody > tr {
      &:hover > td {
        background: #f8f9ff !important;
      }
    }
  }
}

.user-info-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .user-avatar {
    .avatar {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
  
  .user-details {
    flex: 1;
    min-width: 0;
    
    .user-name {
      font-weight: 500;
      color: #333;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .user-account {
      font-size: 12px;
      color: #999;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.user-profile {
  color: #666;
  line-height: 1.4;
  max-width: 200px;
  word-break: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.role-tag {
  font-weight: 500;
  
  .anticon {
    margin-right: 4px;
  }
}

.time-cell {
  .date {
    font-weight: 500;
    color: #333;
    margin-bottom: 2px;
  }
  
  .time {
    font-size: 12px;
    color: #999;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  
  .delete-btn {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-manage-page {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    
    .header-content .page-title {
      font-size: 24px;
    }
    
    .header-stats {
      align-self: stretch;
      
      .stat-item {
        width: 100%;
      }
    }
  }
  
  .search-section {
    .search-actions {
      justify-content: center;
      margin-top: 16px;
    }
  }
  
  .users-table {
    :deep(.ant-table) {
      .ant-table-thead > tr > th,
      .ant-table-tbody > tr > td {
        padding: 12px 8px;
      }
    }
  }
  
  .user-info-cell {
    gap: 8px;
    
    .user-avatar .avatar {
      width: 32px !important;
      height: 32px !important;
    }
  }
}

@media (max-width: 576px) {
  .action-buttons {
    flex-direction: column;
    gap: 4px;
    
    .ant-btn {
      width: 100%;
    }
  }
}
</style>
